<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="SPU名称"> <el-input placeholder="请输入SPU名称" v-model="spu.spuName"></el-input></el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option :label="tm.tmName" :value="tm.id" v-for="(tm, index) in tradeMarkList" :key="tm.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" placeholder="描述" v-model="spu.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <!-- 上传图片 action：上传的地址，list-type：文件列表的类型，on-preview：文件列表的预览图，on-remove：删除预览图，file-list：展示预览图列表 -->
        <el-upload action="/api/admin/product/fileUpload" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleSuccess" :file-list="spuImageList">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${useSelectAttr.length}未选择`" v-model="attrIdAndAttrName">
          <el-option :label="unSelect.name" :value="`${unSelect.id}:${unSelect.name}`" v-for="(unSelect, index) in useSelectAttr" :key="unSelect.id"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" style="margin-left: 5px" :disabled="!attrIdAndAttrName" @click="addSaleAttr">添加销售属性</el-button>
        <!-- 展示当前spu的销售属性 -->
        <el-table style="width: 100%; margin-top: 20px" border :data="spu.spuSaleAttrList">
          <el-table-column type="index" label="序号" width="80px" align="center"> </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="width"> </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template #default="{ row, $index }">
              <!-- el-tag：展示输入的spu属性 -->
              <el-tag :key="tag.id" v-for="tag in row.spuSaleAttrValueList" closable :disable-transitions="false" @close="handleClose(row, $index)">
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" :ref="$index" size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)"> </el-input>
              <!-- 切换显示与输入 上面类似与input下面类似与span -->
              <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(row)" style="margin-top: 5px">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150px">
            <template #default="{ row, $index }">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="spu.spuSaleAttrList.splice($index, 1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdate">保存</el-button>
        <el-button type="" @click="goScreen">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'SpuForm',
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      //注意：在直接点击添加SPU属性值时，spu是一个空对象，只有输入SPU名称时才会自动添加spuName收集的数据
      spu: {
        //三级分类的id
        category3Id: '',
        // 品牌的描述
        description: '',
        tmId: '', //品牌id
        // spu图片的信息
        spuImageList: [
          /* {
            id: 0,
            imgName: '',
            imgUrl: '',
            spuId: 0,
          }, */
        ],
        // spu的名称
        spuName: '',
        // 销售属性
        spuSaleAttrList: [
          /* {
            baseSaleAttrId: 0,
            id: 0,
            saleAttrName: '',
            spuId: 0,
            spuSaleAttrValueList: [
              {
                baseSaleAttrId: 0,
                id: 0,
                isChecked: '',
                saleAttrName: '',
                saleAttrValueName: '',
                spuId: 0,
              },
            ],
          }, */
        ],
      }, //存储spu的数据
      tradeMarkList: [], //存储品牌信息
      spuImageList: [], //存储spu图片
      saleAttrList: [], //存储销售属性
      attrIdAndAttrName: '', //收集未选择的销售属性id
    }
  },
  methods: {
    //照片墙的删除功能
    handleRemove(file, fileList) {
      //  file：删除的图片  fileList：还没有删除的图片
      this.spuImageList = fileList
    },
    // 照片墙的预览列表
    handlePictureCardPreview(file) {
      //将图片的地址赋值给dialogImageUrl
      this.dialogImageUrl = file.url
      //控制图片的放大预览
      this.dialogVisible = true
    },
    // 添加图片成功的处理函数
    handleSuccess(response, file, fileList) {
      //response：添加成功服务器返回的信息, file：上传的图片, fileList：展示图片的数据包括上传图的数据
      this.spuImageList.push(file)
    },
    //自定义事件(取消按钮的处理函数)
    goScreen() {
      this.spuImageList = []
      this.$emit('changeScreen', { screeen: 1, flag: this.spu.id ? '修改' : '添加' })
      //  清理数据  _data：组件示例上的data数据，$options：组件示例上的配置项
      Object.assign(this._data, this.$options.data())
      this.spuImageList = []
    },
    //初始化spu的数据
    async initSpuData(row) {
      // 获取spu的基本信息
      let res = await this.$api.spu.reSpu({ spuId: row.id })
      if (res.code == 200) {
        this.spu = res.data
      }
      // 获取品牌信息
      let res2 = await this.$api.spu.reqTradeMarkList()
      if (res2.code == 200) {
        this.tradeMarkList = res2.data
      }
      //获取spu图片
      let res3 = await this.$api.spu.reSpuImageList({ spuId: row.id })
      if (res3.code == 200) {
        // this.spuImageList = res3.data
        let listUrl = res3.data
        // 由于照片墙的file-list属性需要的类型时[{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]，所以需要处理服务器的照片数据
        listUrl.forEach((item) => {
          this.spuImageList.push({ name: item.imgName, url: item.imgUrl })
        })
      }
      //获取销售属性
      let res4 = await this.$api.spu.reqBaseSaleAttrList()
      if (res4.code == 200) {
        this.saleAttrList = res4.data
      }
    },
    //删除销售属性值的操作（el-tag）
    handleClose(row, index) {
      row.spuSaleAttrValueList.splice(index, 1)
    },
    // 切换输入与显示（输入）
    addSaleAttrValue(row) {
      // row.inputVisible = true //显示输入框，不是响应式数据
      this.$set(row, 'inputVisible', true)
      // row.inputValue:收集input框中的响应式数据
      this.$set(row, 'inputValue', '')
    },
    // el-input失去焦点的事件
    handleInputConfirm(row) {
      row.inputVisible = false
      // 结构出row中的数据以展示在el-tage中
      const { baseSaleAttrId, inputValue } = row
      //新增的销售属性不能为空且不能重复
      if (inputValue.trim() === '') {
        this.$message({ message: '属性值为空', type: 'warning' })
        return
      }
      let a = row.spuSaleAttrValueList.some((item) => {
        return item.saleAttrValueName == inputValue
      })
      if (a) {
        this.$message({ message: '属性值重复', type: 'warning' })
        return
      }
      let newSaleAttrvalue = { baseSaleAttrId, saleAttrValueName: inputValue }
      row.spuSaleAttrValueList.push(newSaleAttrvalue)
    },
    //添加销售属性
    addSaleAttr() {
      // 把收集到的销售属性进行处且添加spu的spuSaleAttrList里面的spuSaleAttrValueList，好在下面的table进行展示
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(':')
      let newAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] }
      this.spu.spuSaleAttrList.push(newAttr)
      this.attrIdAndAttrName = ''
    },
    //保存或者修改（保存按钮）
    async addOrUpdate() {
      //整理带给服务器的参数
      this.spu.spuImageList = this.spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: item.response ? item.response.data : item.url,
        }
      })
      //发送数据
      let res = await this.$api.spu.reqAddOrUpdateSpu(this.spu)
      if (res.code == 200) {
        this.$message({ type: 'success', message: '保存成功' })
        // 子组件通知父组件修改场景
        this.$emit('changeScreen', { screeen: 1, flag: this.spu.id ? '修改' : '添加' })
      } // 清理数据
      Object.assign(this._data, this.$options.data())
    },
    //点击添加SPU按钮，获取品牌信息
    async addSpuDate(category3Id) {
      // 收集三级分类的id
      this.spu.category3Id = category3Id
      //获取品牌信息
      let res = await this.$api.spu.reqTradeMarkList()
      if (res.code == 200) {
        this.tradeMarkList = res.data
      }
      //获取销售属性
      let res2 = await this.$api.spu.reqBaseSaleAttrList()
      if (res2.code == 200) {
        this.saleAttrList = res2.data
      }
    },
  },
  computed: {
    // 计算还未选择的商品属性(saleAttrList:3个销售属性颜色，版本，尺寸；spu.spuSaleAttrList：当前商品的属性)
    useSelectAttr() {
      return this.saleAttrList.filter((item) => {
        return this.spu.spuSaleAttrList.every((item1) => {
          return item.name != item1.saleAttrName
        })
      })
    },
  },
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>